package com.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author ZhaoDong
 * @date 2022/10/31 14:28
 * @description leetcode
 */
public class TestAtomic {
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            Integer reference = atomicStampedReference.getReference();

            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("stamp1 = " + stamp);
            System.out.println("reference 1= " + reference);

            atomicStampedReference.compareAndSet(reference, 101, stamp, stamp + 1);
            atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), stamp + 1);


            System.out.println("stamp2 = " + atomicStampedReference.getStamp());
            System.out.println("reference 2= " + atomicStampedReference.getReference());

        }, "t1").start();

        new Thread(() -> {
            int stamp = atomicStampedReference.getStamp();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(atomicStampedReference.compareAndSet(100, 2022, atomicStampedReference.getStamp(), stamp + 1));

        }).start();


    }
}
